/*
 * @Author: likang xie
 * @Date: 2019-06-03 13:38:32
 * @Usage request方法二次封装
 */

import config from "@/config";
import toast from "@/utils/toast";

let showMessage = true; // 接口请求是否输出
let codes = [401, 402, 403, 404];

// ---- 封装增、删、改、查方法 ----
let request = new Object();

["post", "del", "put", "get"].forEach((method) => {
  request[method] = (
    url,
    params,
    flag = true,
    headers = {
      "content-type": "application/x-www-form-urlencoded",
    },
    extra = {
      loading: true,
      toast: true,
    }
  ) =>
    new Promise((resolve, reject) => {
      // 显示loading
      if ((extra && typeof extra.loading == "undefined") || extra.loading) {
        uni.showLoading({
          title: extra.title || "正在请求数据",
          mask: true,
        });
      }

      // let header = {};
      // header["Content-type"] = "application/x-www-form-urlencoded";

      // 开始请求
      uni
        .request({
          url: config.remote + url,
          headers,
          data: flag ? { ...params } : params,
          method,
        })
        .then((chunk) => {
          // setTimeout(() => {
          //   loading && uni.hideLoading();
          //   loading = "";
          // }, 500);

          let [err, res] = chunk;

          if (res.statusCode == 404) return toast("未找到指定接口");

          if (res) {
            let { code, data, message } = res.data;

            uni.hideLoading();
            resolve(res.data);

            // 刷新
            if (code == 200 && extra.refresh) {
              uni.stopPullDownRefresh();
              toast("已更新数据");
            }

            // 服务端报错
            if (code != 200 && !codes.includes(code) && extra.toast)
              toast(message || "服务器异常");

            // 未授权
            // #ifndef H5
            if (codes.includes(code)) {
              uni.navigateTo({
                url: "/pages/user/authorize",
              });
            }
            // #endif

            showMessage &&
              console.log(
                "执行请求：%s，返回参数：%o，请求参数：%o",
                url,
                res.data,
                params
              );
          } else {
            reject(err);
          }
        });
    });
});

export default request;
